package com.example.shutdown_v1.service;

import com.example.shutdown_v1.entity.Sensor;
import com.example.shutdown_v1.entity.SwitchStateRecord;
import com.example.shutdown_v1.repository.SensorRepository;
import com.example.shutdown_v1.repository.SwitchStateRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 开关状态记录服务
 * 负责记录状态变化历史
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SwitchStateRecordService {

    private final SwitchStateRecordRepository stateRecordRepository;
    private final SensorRepository sensorRepository;

    /**
     * 记录状态变化
     * @param sensorId 传感器ID
     * @param currentState 当前状态
     * @param euclideanDistance 欧氏距离
     * @return 是否为状态变化（true=状态改变，false=状态未变）
     */
    @Transactional
    public boolean recordStateChange(String sensorId, String currentState, double euclideanDistance) {
        // 获取传感器信息
        Optional<Sensor> sensorOpt = sensorRepository.findBySensorId(sensorId);
        if (sensorOpt.isEmpty()) {
            log.warn("[{}] 传感器不存在，无法记录状态", sensorId);
            return false;
        }
        
        Sensor sensor = sensorOpt.get();
        
        // 查询最新状态记录
        Optional<SwitchStateRecord> latestRecordOpt = 
                stateRecordRepository.findFirstBySensorIdOrderByRecordTimeDesc(sensorId);
        
        String previousState = null;
        boolean isStateChanged = false;
        
        if (latestRecordOpt.isPresent()) {
            previousState = latestRecordOpt.get().getCurrentState();
            isStateChanged = !currentState.equals(previousState);
        } else {
            // 第一次记录，视为状态变化
            isStateChanged = true;
        }
        
        // 只有状态变化时才记录
        if (isStateChanged) {
            // 检查传感器是否有shopId，没有则跳过记录
            if (sensor.getShopId() == null) {
                log.warn("[状态记录] 传感器 {} 没有绑定店铺，跳过状态记录", sensorId);
                return false;
            }
            
            SwitchStateRecord record = new SwitchStateRecord();
            record.setSensorId(sensorId);
            record.setShopId(sensor.getShopId());
            record.setInstallPosition(sensor.getInstallPosition());
            record.setPreviousState(previousState);
            record.setCurrentState(currentState);
            record.setEuclideanDistance(euclideanDistance);
            record.setRecordTime(LocalDateTime.now());
            
            stateRecordRepository.save(record);
            
            log.info("[{}] 状态变化: {} -> {}, 距离={}", 
                    sensorId, previousState, currentState, euclideanDistance);
        }
        
        return isStateChanged;
    }
    
    /**
     * 获取传感器当前状态
     */
    public Optional<String> getCurrentState(String sensorId) {
        return stateRecordRepository.findFirstBySensorIdOrderByRecordTimeDesc(sensorId)
                .map(SwitchStateRecord::getCurrentState);
    }
}

